package org.ricks.common.db;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author chenwei
 * @Title:
 * @Package
 * @Description:
 * @date 2020/12/2114:07
 */
public class ScalarHandler<T> implements ResultSetHandler<T> {
    private final int columnIndex;
    private final String columnName;

    public ScalarHandler() {
        this(1, (String)null);
    }

    public ScalarHandler(int columnIndex) {
        this(columnIndex, (String)null);
    }

    public ScalarHandler(String columnName) {
        this(1, columnName);
    }

    private ScalarHandler(int columnIndex, String columnName) {
        this.columnIndex = columnIndex;
        this.columnName = columnName;
    }

    public T handle(ResultSet rs) throws SQLException {
        if (rs.next()) {
            return (T) (this.columnName == null ? rs.getObject(this.columnIndex) : rs.getObject(this.columnName));
        } else {
            return null;
        }
    }
}

